//
//  WmcCreateTeamVM.swift
//  YPWatermarkCamera
//
//  Created by yupao_ios_macmini06 on 2022/9/15.
//

import Foundation
import RxRelay
import SVProgressHUD

// MARK: - [WmcCreateTeamVM]

class WmcCreateTeamVM: WmcBaseVM {
    enum OperationType: String {
        case create
        case modify

        var text: String {
            switch self {
            case .create:
                return "创建"
            case .modify:
                return "保存"
            }
        }
    }

    /// 团队相册
    var teamAblum: WmcMediaTeamAlbumModel?
    /// 操作类型
    var opType: OperationType = .create

    /// 复制团队号
    /// - Parameter teamId: teamId description
    /// - Returns: description
    func copyTeamId(teamId: String? = "") {
        let pasteboard = WmcPasteboard()
        pasteboard.plainText = teamId ?? ""
        pasteboard.saveToPasteboard()
        WmcHudManager.toast("复制成功")
    }

    /// 创建团队
    /// - Parameter teamName: 团队名称
    /// - Returns: description
    func createTeam(teamName: String, succeed: ((_ resp: WmcCreateTeamResult) -> Void)?) {
        SVProgressHUD.show()
        WmcMediaTeamManagerAPI.createTeam(name: teamName).subscribe { res in
            guard let succeed = succeed else {
                return
            }
            /// 创建团队成功 发送通知，通知刷新
            WmcNotificationManager.shared.post(type: .createTeamSucceed, object: nil)
            /// 同步配置
            let config = WmcMediaAlbumConfigurationModel()
            config.albumType = 1
            config.isSync = true
            config.name = teamName
            config.albumId = res.albumId ?? 0
            config.busId = res.teamId ?? 0
            WmcPreferenceSettingsManager.addTeamSyncConfig(model: config)
            succeed(res)
            /// 计数加一 处理第一次进入团队 示例展示
            if var count: Int = WmcUserdefault.object(forKey: .Tips.Home.enterTeamAlbumCount) {
                count = count + 1
                WmcUserdefault.save(value: count, forKey: .Tips.Home.enterTeamAlbumCount)
            } else {
                WmcUserdefault.save(value: 0, forKey: .Tips.Home.enterTeamAlbumCount)
            }
            SVProgressHUD.dismiss()
        } onError: { error in
            WmcHudManager.toast(error)
            SVProgressHUD.dismiss()
        }.disposed(by: rx.disposeBag)
    }

    /// 修改团队名称
    /// - Parameters:
    ///   - teamId: teamId description
    ///   - teamName: teamName description
    /// - Returns: description
    func updateTeamName(teamName: String, succeed: (() -> Void)?) {
        guard let teamId = self.teamAblum?.teamId else {
            return
        }
        WmcHudManager.loading()
        WmcMediaTeamManagerAPI.updateTeamName(id: "\(teamId)", name: teamName).subscribe { res in
            WmcHudManager.dismiss()
            guard let succeed = succeed else {
                return
            }
            succeed()
        } onError: { error in
            WmcHudManager.toast(error)
            WmcHudManager.dismiss()
        }.disposed(by: rx.disposeBag)
    }
}

extension WmcCreateTeamVM {
    /// 找到对应的团队相册ID
    /// - Parameters:
    ///   - teamId: teamId description
    ///   - succeed: succeed description
    /// - Returns: description
    func findCurrentSpecificTeam(teamId: Int, succeed: ((_ teamAlbum: WmcMediaTeamAlbumModel) -> Void)?) {
        WmcMediaTeamAlbumAPI.fetchTeamAlbumList().subscribe { list in
            guard let succeed = succeed else { return }
            list.forEach { album in
                if teamId == album.teamId {
                    succeed(album)
                }
            }
        } onError: { error in
            WmcHudManager.toast(error)
        }.disposed(by: rx.disposeBag)
    }
}

extension WmcCreateTeamVM {
    func updateAblumInfo(_ model: WmcMediaTeamAlbumModel) {
        WmcCloudAlbumInfoDBManager.query { list in
            let isContain = list.contains { item in
                return item.albumId == model.albumId
            }
            // 保存一下最新的照片id
            if isContain {
                WmcCloudAlbumInfoDBManager.update(albumId: model.albumId, latestPhotoId: model.maxDbId)
            } else {
                WmcCloudAlbumInfoDBManager.insert(albumId: model.albumId, latestPhotoId: model.maxDbId)
            }
        }
    }
}
